//
//  TopicDetailViewController.m
//  miaopai
//
//  Created by duyifang on 15/11/13.
//  Copyright © 2015年 Crow Zhang. All rights reserved.
//

#import "TopicDetailViewController.h"
#import "TopicWaterFallLayout.h"
#import "AutoadaptationFrame.h"
#import "CustomerNetworking.h"
#import "TopicDetailCollectionViewCell.h"
#import "Channel.h"
#import "TopicDetailModel.h"
#import "HeaderCollectionViewCell.h"
#import <AFNetworking.h>
#import <MJRefresh.h>
#import <UINavigationBar+Awesome.h>
#import "VideoDetailViewController.h"
#import "SCCatWaitingHUD.h"
#import <SVProgressHUD.h>

#define NAVBAR_CHANGE_POINT 50

@interface TopicDetailViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout,  TopicWaterFallLayout>

@property(nonatomic, retain) UICollectionView *collectionView;

@property(nonatomic, retain) NSMutableArray *modelArray;

@property(nonatomic, assign)NSInteger loadTimes;

@property(nonatomic, retain)TopicDetailModel *topicDetail;

@end

@implementation TopicDetailViewController

- (void)dealloc
{
    [_collectionView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[SCCatWaitingHUD sharedInstance] animateWithInteractionEnabled:YES];
    self.title = self.topicName;
    self.loadTimes = 1;
    self.navigationItem.hidesBackButton = NO;
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"返回";
    self.navigationItem.backBarButtonItem = backItem;
    [backItem release];
    
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName,nil]];
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    
    self.modelArray = [NSMutableArray array];
    
    [self creatSubView];
    [self downloadData];
    
}

- (void)downloadData
{
    
    NSString *urlStr = [NSString stringWithFormat:@"http://api.miaopai.com/m/v2_topic.json?os=ios&page=%ld&per=20&stpid=%@&type=2&unique_id=d148d7c2b9c27f685d9be7639517be5e3661826668&version=6.2.1", self.loadTimes,self.stpid];
    if (self.stpid == nil) {
        urlStr = [[NSString stringWithFormat:@"http://api.miaopai.com/m/v2_topic.json?os=ios&page=1&per=20&topicname=%@&type=2&unique_id=d148d7c2b9c27f685d9be7639517be5e3661826668&version=6.2.1", self.topicName] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    [manager.requestSerializer setValue:@"miaopai" forHTTPHeaderField:@"vend"];
    manager.securityPolicy.allowInvalidCertificates = YES;
    [manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id response) {
        [[SCCatWaitingHUD sharedInstance] stop];
        NSDictionary *bigDic = response;
        self.topicDetail = [TopicDetailModel topicDetailModelWithDictionary:bigDic];
        if ([[bigDic objectForKey:@"result"] count] == 0) {
            [_collectionView.mj_footer endRefreshingWithNoMoreData];
            return ;
        }
        NSArray *topicArray = [bigDic objectForKey:@"result"];
        for (NSDictionary *dic in topicArray) {
            Channel *channel = [Channel channelWithDic:[dic objectForKey:@"channel"]];
            [_modelArray addObject:channel];
        }
        [_collectionView reloadData];
        [_collectionView.mj_footer endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[SCCatWaitingHUD sharedInstance] stop];
        [SVProgressHUD showErrorWithStatus:@"网络错误!"];
    }];
}

- (void)creatSubView
{
    TopicWaterFallLayout *flowLayout = [[TopicWaterFallLayout alloc] init];
    flowLayout.delegate = self;
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView setContentInset:UIEdgeInsetsMake(-64, 0, -96, 0)];
    _collectionView.backgroundColor = [UIColor colorWithRed:0.9063 green:0.9063 blue:0.9063 alpha:1.0];
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.loadTimes++;
        [self downloadData];
    }];
    [_collectionView registerClass:[HeaderCollectionViewCell class] forCellWithReuseIdentifier:@"headerCollectionViewCell"];
    [_collectionView registerClass:[TopicDetailCollectionViewCell class] forCellWithReuseIdentifier:@"TopicDetailCollectionViewCell"];
    [self.view addSubview:_collectionView];
    [_collectionView release];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    else
    {
        return _modelArray.count;
    }
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        HeaderCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"headerCollectionViewCell" forIndexPath:indexPath];
        cell.topicDetail = self.topicDetail;
        return cell;
    }
    else
    {
        TopicDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TopicDetailCollectionViewCell" forIndexPath:indexPath];
        cell.channel = [self.modelArray objectAtIndex:indexPath.row];
        cell.backgroundColor = [UIColor whiteColor];
        cell.layer.cornerRadius = 5;
        cell.layer.masksToBounds = YES;
        return cell;
    }
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return CGSizeMake(kWidth, kWidth * 1.5);
    }else
    {
        Channel *channel = [self.modelArray objectAtIndex:indexPath.row];
        CGFloat itemWidth = (self.view.frame.size.width - 30) / 2;
        if ([channel.ext.t isEqualToString:@""]) {
            CGFloat pictureHeight = itemWidth;
            return CGSizeMake(itemWidth, pictureHeight + 5);
        }else
        {
            CGFloat pictureHeight = itemWidth + 20;
            CGFloat wordsHeight = [AutoadaptationFrame heightOfLabel:channel.ext.t andTextFont:[UIFont systemFontOfSize:13] andLabelWidth:itemWidth - 10];
            return CGSizeMake(itemWidth, pictureHeight + wordsHeight + 20);
        }
    }
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    UIColor * color = [UIColor colorWithWhite:0.961 alpha:1.000];
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY > NAVBAR_CHANGE_POINT) {
        CGFloat alpha = MIN(1, 1 - ((NAVBAR_CHANGE_POINT + 64 - offsetY) / 64));
        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:alpha - 0.05]];
        [self.navigationController.navigationBar setTintColor:[UIColor colorWithWhite:1 - alpha alpha:1]];
        [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithWhite:1 - alpha alpha:1], NSForegroundColorAttributeName,nil]];
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    } else {
        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:0]];
        [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
        [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName,nil]];
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.collectionView.delegate = nil;
    [self.navigationController.navigationBar lt_reset];
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor], NSForegroundColorAttributeName,nil]];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.collectionView.delegate = self;
    [self scrollViewDidScroll:self.collectionView];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    UIView * view = [self.tabBarController.view.subviews lastObject];
    [UIView animateWithDuration:0.5 animations:^{
        view.frame = CGRectMake(0, kHeight + 100, kWidth, 48);
    }];
    
    if (self.modelArray.count > 0) {
        UIColor * color = [UIColor colorWithWhite:0.961 alpha:1.000];
        CGFloat offsetY = self.collectionView.contentOffset.y;
        NSLog(@"%lf", self.collectionView.contentOffset.y);
        if (offsetY > NAVBAR_CHANGE_POINT) {
            CGFloat alpha = MIN(1, 1 - ((NAVBAR_CHANGE_POINT + 64 - offsetY) / 64));
            [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:alpha - 0.05]];
            [self.navigationController.navigationBar setTintColor:[UIColor colorWithWhite:1 - alpha alpha:1]];
            [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithWhite:1 - alpha alpha:1], NSForegroundColorAttributeName,nil]];
            [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
        } else {
            [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:0]];
            [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
            [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName,nil]];
            [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
        }

    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    VideoDetailViewController *videoDetailViewController = [[VideoDetailViewController alloc] init];
    if (indexPath.section == 0) {
        videoDetailViewController.scid = self.topicDetail.channel.scid;
    }else
    {
        videoDetailViewController.scid = [[_modelArray objectAtIndex:indexPath.row] scid];
    }
    [self.navigationController pushViewController:videoDetailViewController animated:YES];
    [videoDetailViewController release];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
